/**
 * 频率分析仪
 * @param analyserNode
 * @param callBack
 */
export const audioAnalogy = (analyserNode:AnalyserNode,callBack:Function) => {
    loopFn(() => {
        const audioArray = new Uint8Array( analyserNode.frequencyBinCount)
        analyserNode.getByteFrequencyData(audioArray)
        callBack && callBack(audioArray)
    })
}

/**
 * 可视化模板
 * @param canvas 目标元素
 * @param data 数据
 */
export const drawAnalogyDataVModelA = (canvas:HTMLCanvasElement | null,data:ArrayBuffer) => {
    if (!canvas) return console.log('未获取到元素')
    const ctx = canvas.getContext("2d");
    if(!ctx) return console.log('获取canvas画笔失败')
    const WIDTH = canvas.width;
    const HEIGHT = canvas.height;

    const lineWidth = 2.3; //bar宽度
    const gap = 0.7; // bar边距
    const ratio = data.byteLength / WIDTH // 频谱宽度换算比
    const count = Math.round(WIDTH / (lineWidth + gap)) // bar数量
    const heightRatio = 256
    ctx.strokeStyle = "red";
    ctx.lineCap = "butt";
    ctx.lineWidth = lineWidth;
    ctx.clearRect(0, 0, WIDTH, HEIGHT); //清空画布
    for (let i = 0; i < count; i++) {
        // @ts-ignore
        const value = Math.round((data[Math.floor(i  * ratio)] / heightRatio) * HEIGHT * 0.9);
        ctx.beginPath();
        ctx.moveTo(i * (lineWidth + gap) + gap / 2, HEIGHT);
        ctx.lineTo(i * (lineWidth + gap) + gap / 2, HEIGHT  - value);
        ctx.stroke();
    }
}

const loopFn = (fn:Function) => {
    if(fn){
        fn()
        window.requestAnimationFrame(() => loopFn(fn))
    }
}
